package com.lovnx.web;

import java.io.IOException;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

@RestController
public class ComputeController {

    private final Logger logger = Logger.getLogger(getClass());

    @Autowired
    private DiscoveryClient eurekaClient;
    
    @Autowired
    private OkHttpClient okHttpClient;

    @RequestMapping(value = "/add" ,method = RequestMethod.GET)
    public String add(@RequestParam Integer a, @RequestParam Integer b) {
        ServiceInstance instance = eurekaClient.getLocalServiceInstance();
        Integer r = a + b;
        logger.info("/add, host:" + instance.getHost() + ", service_id:" + instance.getServiceId() + ", result:" + r);
        return "From Service-A, Result is " + r;
    }

    //A服务调用B服务
    @RequestMapping(value="testServiceB",method=RequestMethod.GET)
    public String testServiceB(@RequestParam Integer a,@RequestParam Integer b){
    	logger.info("/testServiceB, Integer:" + a + ", Integer:" + b);
    	RestTemplate restTemplate=new RestTemplate();
    	return restTemplate.getForObject("http://localhost:7076/add?a="+a+"&b="+b, String.class);
    }
    
    //A服务调用B服务
    @RequestMapping(value="okhttp",method=RequestMethod.GET)
    public String okhttp(@RequestParam Integer a,@RequestParam Integer b) throws IOException{
    	logger.info("/okhttp, Integer:" + a + ", Integer:" + b);
        Request request = new Request.Builder().url("http://localhost:7076/add?a="+a+"&b="+b).get().build();  //service4
        Response response = okHttpClient.newCall(request).execute();
        String result = response.body().string();
        return result;
    }
    
}